#include "list.h"



void SLTPrint(SLTNode* phead)
{
	if (phead == NULL)
	{
		cout << "NULL" << endl;
	}
	SLTNode* h = phead;

	while (h != NULL)
	{
		printf("%d ", h->data);
		h = h->next;
	}
	printf("\n");
}

void SLTPushBack(SLTNode** pphead, SLTDataType x)
{
	SLTNode* tem = (SLTNode*)malloc(sizeof(SLTNode));
	assert(tem);
	tem->data = x;
	tem->next = NULL;

	if (*pphead == NULL)
	{
		*pphead = tem;
	}
	else
	{
		SLTNode* h = *pphead;
		while (h->next != NULL)
		{
			h = h->next;
		}

		h->next = tem;
	}
}

void SLTPushFront(SLTNode** pphead, SLTDataType x)
{
	SLTNode* tem = (SLTNode*)malloc(sizeof(SLTNode));
	assert(tem);
	tem->data = x;
	tem->next = NULL;

	if (*pphead == NULL)
	{
		*pphead = tem;
	}
	else
	{
		tem->next = *pphead;
		*pphead = tem;
	}
}

void SLTPopBack(SLTNode** pphead)
{
	if (*pphead == NULL)
	{
		return;
	}
	else
	{
		SLTNode* tem = *pphead;
		while (tem->next != NULL && tem->next->next != NULL)
		{
			tem = tem->next;
		}
		if (tem->next == NULL)
		{
			free(tem);
			*pphead = NULL;
		}
		else
		{
			free(tem->next);
			tem->next = NULL;
		}

	}
}

void SLTPopFront(SLTNode** pphead)
{
	if (*pphead == NULL)
	{
		return;
	}
	SLTNode* tem = (*pphead)->next;
	free(*pphead);
	*pphead = tem;
}

SLTNode* SLTFind(SLTNode* phead, SLTDataType x)
{
	while (phead != NULL)
	{
		if (phead->data == x)
		{
			return phead;
		}
		phead = phead->next;
	}
	return nullptr;
}

void SLTInsert(SLTNode** pphead, SLTNode* pos, SLTDataType x)
{
	assert(pos);
	if (*pphead == NULL || pos == *pphead)
	{
		SLTPushFront(pphead, x);
		return;
	}

	SLTNode* tem = (SLTNode*)malloc(sizeof(SLTNode));
	assert(tem);
	tem->data = x;
	tem->next = NULL;

	SLTNode* p = *pphead;
	while (p->next != pos && p != NULL)
	{
		p = p->next;
	}

	if (p != NULL)
	{
		p->next = tem;
		tem->next = pos;
	}
}

void SLTErase(SLTNode** pphead, SLTNode* pos)
{
	if (*pphead == NULL || pos == NULL)
	{
		return;
	}
	if (*pphead == pos)
	{
		SLTPopFront(pphead);
		return;
	}

	SLTNode* tem = *pphead;
	while (tem->next != pos && tem != NULL)
	{
		tem = tem->next;
	}

	if (tem != NULL)
	{
		SLTNode* temp = pos->next;
		free(pos);
		tem->next = temp;
	}
}

void SLTInsertAfter(SLTNode* pos, SLTDataType x)
{
	if (pos == NULL)
	{
		return;
	}
	SLTNode* tem = (SLTNode*)malloc(sizeof(SLTNode));
	assert(tem);
	tem->data = x;
	tem->next = NULL;

	SLTNode* pxx = pos->next;

	pos->next = tem;
	tem->next = pxx;
}

void SLTEraseAfter(SLTNode* pos)
{
	if (pos == NULL ||pos->next == NULL)
	{
		return;
	}

	SLTNode* tem = pos->next->next;

	free(pos->next);
	pos->next = tem;
}

void SListDesTroy(SLTNode** pphead)
{
	if (*pphead == NULL)
	{
		return;
	}
	SLTNode* tem = (*pphead)->next;
	while (tem != NULL)
	{
		free(*pphead);
		*pphead = tem;
		tem = tem->next;
	}
	free(*pphead);
	*pphead = NULL;
}
